** this short program estimates a mixed logit for each imputed data **
** it then saves the parameters and values of interest for each iteration **
** be certain that you have installed: **
	** the "mixlogit" package and **
	** the "eststo" package before estimating **
	
** first, set your directory to the replication folder **
** and execute the script needed for the posterior draws **

	clear
	cd "replication"
	do "simUtils.do"

** now, set more off and set the loop to run through each imputed data **
	set more off
	forvalues iteration = 1/10{

	** read in the data **
		use "data`iteration'.dta", clear

	** fix the economic perceptions variable to have minimum = 0 **
		egen min_economyGov = min(economyGov)
		replace economy = economy + abs(min_economyGov)
		replace economyGov = economy * gov

	** create the economy-compromise interaction with the new economy variable **
		gen compEconSub = economyGov*govCompSub

	** estimate the simple model and save the results **
		mixlogit vote, rand(gov govCompSub lr lrGov economyGov) group(group) 
		eststo estLrS_`iteration'

	** now estimate the full model and save the results **
		mixlogit vote, rand(gov govCompSub lr lrGov economyGov compLrGovSub compEconSub) group(group) 
		eststo estLrF_`iteration'

	** take the posterior draws **
		tempname b V sig dfsig
		matrix `b' = e(b)                            
		matrix `V' = e(V)                            
		local N = `e(N)'                             
		capture drop bbt*
		_simp, b(`b') v(`V') s(1000) g(bbt)

	** save the draws to a separate file **
		preserve
			keep bbt*
			saveold "fullBeta`iteration'.dta", version(12) replace 
		restore

	** now extract and save the random coefficient estimates **
		mixlbeta gov govCompSub lr lrGov economyGov compLrGovSub compEconSub, nrep(1000) saving("mixBetas`iteration'.dta") replace

	** sort the original data and save it **
		sort group
		saveold "hold`iteration'.dta", version(12) replace 

	** now fethch the random coefficients and sort them to merge with the original data **
		use "mixBetas`iteration'.dta", clear
		sort group
		rename gov randGov
		rename govCompSub randComp
		rename lr randLr
		rename lrGov ranLrgGov
		rename economyGov randEcon
		rename compLrGovSub randDisc		
		rename compEconSub randDiscEcon

	** merge it **
		merge group using "hold`iteration'.dta"
	
	** and save the complete data -- we'll need this for the secondary analysis **
		saveold "mixBetas`iteration'.dta", version(12) replace 

	}

 
	** this bit here will write a csv of the results from all models **
		# delimit ;
			esttab estLrS_1 estLrS_2 estLrS_3 estLrS_4 estLrS_5 estLrS_6 estLrS_7 estLrS_8 estLrS_9 estLrS_10 estLrF_1 estLrF_2 estLrF_3 estLrF_4 estLrF_5 estLrF_6 estLrF_7 estLrF_8 estLrF_9 estLrF_10
			using results.csv, se nostar scalars(ll)
			nodepvars nomtitles replace compress plain;
		#delimit cr
